package com.bruceewu.galleryphoto.utis;

import android.app.Activity;
import android.content.Context;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.view.Window;
import android.view.WindowManager;

import com.bruceewu.galleryphoto.base.App;

public class ScreenUtils {
    private static int screenWith;
    private static int screenHeight;

    public static int dip2px(int dip) {
        final float scale = App.getInstance().getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f);
    }

    public static int getScreenWidth() {
        if (screenWith == 0) {
            WindowManager windowManager = (WindowManager) App.getInstance().getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics dm = new DisplayMetrics();// 创建了一张白纸
            windowManager.getDefaultDisplay().getMetrics(dm);// 给白纸设置宽高
            screenWith = dm.widthPixels;
        }
        return screenWith;
    }

    public static int getScreenHeight() {
        if (screenHeight == 0) {
            WindowManager windowManager = (WindowManager) App.getInstance().getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics dm = new DisplayMetrics();// 创建了一张白纸
            windowManager.getDefaultDisplay().getMetrics(dm);// 给白纸设置宽高
            screenHeight = dm.heightPixels;
        }
        return screenHeight;
    }

    // 比例式 : width / height = screenWidth / screenHeight
    public static Pair<Integer, Integer> scaleSize(int width, int height) {
        int screenWidth = getScreenWidth();
        int screenHeight = getScreenHeight();
        if (width * screenHeight > screenWidth * height) {// 1. 大宽图: 宽度以屏幕宽度为准,高度缩放
            int scaledHeight = (int) (screenWidth * (height * 1.0F / width));
            return new Pair<>(screenWidth, scaledHeight);
        } else if (width * screenHeight < screenWidth * height) {//2. 大高图: 高度以屏幕高度为准,缩放宽度
            int scaledWidth = (int) (screenHeight * (width * 1.0F / height));
            return new Pair<>(scaledWidth, screenHeight);
        } else {// 3. 与屏幕比例一样: 不缩放
            return new Pair<>(screenWidth, screenHeight);
        }
    }

    public static void screenLightOn(Activity activity) {
        Window window = activity.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    public static void screenLightOff(Activity activity) {
        Window window = activity.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
}
